# 文件名: adb_ui_inspector.py
import subprocess
import xml.etree.ElementTree as ET
import os

class ADBUIInspector:
    def __init__(self):
        self.ui_dump_path = "ui.xml"

    def run_adb_command(self, command):
        """运行 ADB 命令并返回输出"""
        try:
            result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            return result.stdout.decode('utf-8').strip()
        except subprocess.CalledProcessError as e:
            raise Exception(f"ADB Error: {e.stderr.decode('utf-8').strip()}")

    def get_device_list(self):
        """获取连接的设备列表"""
        output = self.run_adb_command("adb devices")
        devices = [line.split("\t")[0] for line in output.split("\n")[1:] if line.strip()]
        return devices

    def pull_ui_dump(self):
        """从设备拉取 UI Dump 文件"""
        self.run_adb_command("adb shell uiautomator dump /sdcard/ui.xml")
        self.run_adb_command(f"adb pull /sdcard/ui.xml {self.ui_dump_path}")
        return os.path.exists(self.ui_dump_path)

    def get_control_params_by_resource_id(self, resource_id):
        """通过 resource-id 获取控件参数"""
        if not self.pull_ui_dump():
            raise Exception("Failed to pull UI dump file from device.")

        tree = ET.parse(self.ui_dump_path)
        root = tree.getroot()
        for node in root.iter("node"):
            if node.get("resource-id") == resource_id:
                params = {
                    "resource-id": node.get("resource-id"),
                    "class": node.get("class"),
                    "text": node.get("text"),
                    "bounds": node.get("bounds"),
                    "clickable": node.get("clickable"),
                    "enabled": node.get("enabled"),
                    "visible": node.get("visible")
                }
                return params
        raise Exception(f"Control with resource-id '{resource_id}' not found.")

    def cleanup(self):
        """清理本地生成的文件"""
        if os.path.exists(self.ui_dump_path):
            os.remove(self.ui_dump_path)